package com.tjtt.tdm.fileupload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tjtt.tdm.exception.DaoException;
import com.tjtt.tdm.fileupload.bean.TdmAttachment;
import com.tjtt.tdm.fileupload.service.TdmAttachmentService;

public class FileDownloadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public FileDownloadServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}
//	public void doPost(HttpServletRequest req, HttpServletResponse res)
//			throws ServletException, IOException {
//		
//		// 获取下载路径
//		String id = req.getParameter("id");
//		WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getSession().getServletContext());  
//		TdmAttachmentService tdmAttachmentService =  (TdmAttachmentService)factory.getBean("tdmAttachmentService");
//		TdmAttachment attachment = null;
//		try {
//			attachment = tdmAttachmentService.getOneAttachment(id);
//		} catch (DaoException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		String ctxDir = req.getSession().getServletContext().getInitParameter("filePath");
//		if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
//			ctxDir = ctxDir + File.separatorChar;
//		}
//		String path = ctxDir + attachment.getFilePath();
//		 File obj = new File(path);
//		 if (!obj.exists()) {
//			res.setContentType("text/html;charset=utf-8");
//			res.getWriter().print("指定文件不存在！");
//			return;
//		}
//		//res.setContentType("application/octet-stream");
//		// 读取文件名：用于设置客户端保存时指定默认文件
//		//int index = path.lastIndexOf("\\"); // 前提：传入的path字符串以“\”表示目录分隔符
//		//String fileName = path.substring(index + 1);
//		// 写流文件到前端浏览器
//		ServletOutputStream out = res.getOutputStream();
//		// 中文文件名转码
//		res.setHeader("Content-disposition", "attachment;filename="
//				+ java.net.URLEncoder.encode(attachment.getFileName(), "UTF-8"));
//		BufferedInputStream bis = null;
//		BufferedOutputStream bos = null;
//		try {
//			bis = new BufferedInputStream(new FileInputStream(path));
//			bos = new BufferedOutputStream(out);
//			byte[] buff = new byte[2048];
//			int bytesRead;
//			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//				bos.write(buff, 0, bytesRead);
//			}
//		} catch (IOException e) {
//			throw e;
//		} finally {
//			if (bis != null)
//				bis.close();
//			if (bos != null)
//				bos.close();
//		}
//	}
	public String getFilePath(String dir,String filename) throws IOException
	{
		String filepath="";
		File dirFile=new File(dir);
		File[] files=dirFile.listFiles();
		int num=files.length;
		for(int i=0;i<num;i++)
		{
			File file=files[i];
			if(file.isDirectory())
			{
				String dirSub=file.getAbsolutePath();
				String res=getFilePath(dirSub,filename);
				if(!res.equals(""))
				{
					return res;
				}
			}	
			else 
			{
				String name=file.getName();
				if(name.equals(filename))
				{
					String path=file.getAbsolutePath();
					return path;
				}
			}
		}
		return filepath;
	}
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		// 获取下载路径
		String id = req.getParameter("id");
		WebApplicationContext factory = WebApplicationContextUtils.getRequiredWebApplicationContext(req.getSession().getServletContext());  
		TdmAttachmentService tdmAttachmentService =  (TdmAttachmentService)factory.getBean("tdmAttachmentService");
		TdmAttachment attachment = null;
		try {
			attachment = tdmAttachmentService.getOneAttachment(id);
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String ctxDir = req.getSession().getServletContext().getInitParameter("filePath");
		if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
			ctxDir = ctxDir + File.separatorChar;
		}
		
		String path = ctxDir + attachment.getFilePath();
		//查找文件
//		String filename=attachment.getFileName();
//		int index=path.lastIndexOf("\\");
//		String dir=path.substring(0,index);
//		path=getFilePath(dir,filename); //文件路径
		//
		 File obj = new File(path);
		 if (!obj.exists()) {			 
			//查找文件
			String filename=attachment.getFileName();
			int index=path.lastIndexOf("\\");
			String dir=path.substring(0,index);
			path=getFilePath(dir,filename); //文件路径
			File obj2 = new File(path);
			if (!obj2.exists())
			{
				res.setContentType("text/html;charset=utf-8");
				res.getWriter().print("指定文件不存在！");
				return;
			}	
		}
		//res.setContentType("application/octet-stream");
		// 读取文件名：用于设置客户端保存时指定默认文件
//		int index = path.lastIndexOf("\\"); // 前提：传入的path字符串以“\”表示目录分隔符
//		String fileName = path.substring(index + 1);
		// 写流文件到前端浏览器
		ServletOutputStream out = res.getOutputStream();
		// 中文文件名转码
		res.setHeader("Content-disposition", "attachment;filename="
				+ java.net.URLEncoder.encode(attachment.getFileName(), "UTF-8"));
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(path));
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	

	public void init() throws ServletException {
		// Put your code here
	}
}
